package cn.zhz.cloud.auth.web.service.impl;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.zhz.cloud.auth.web.model.dto.LoginParamDto;
import cn.zhz.cloud.auth.web.model.po.UserPo;
import cn.zhz.cloud.auth.web.service.IAuthService;
import cn.zhz.cloud.auth.web.service.IUserService;
import cn.zhz.cloud.common.model.constant.SqlConstant;
import cn.zhz.cloud.common.model.exception.BusinessException;
import cn.zhz.cloud.token.dto.CurrentUserDto;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import static cn.zhz.cloud.auth.web.constant.AuthConstant.LOGIN_AES_CRYPTO_KEY_BYTE;
import static cn.zhz.cloud.token.constant.TokenConstant.*;

/**
 * @author ZHZ
 * @since 2022-11-08
 */

@Service
@RequiredArgsConstructor
public class AuthServiceImpl implements IAuthService {

    private final IUserService iUserService;

    /**
     * 登录
     *
     * @param loginParamDto
     * @return
     */
    @Override
    public String login(LoginParamDto loginParamDto) {
        String username = loginParamDto.getUsername();
        String password = loginParamDto.getPassword();

        UserPo userPo = iUserService.getOne(Wrappers.lambdaQuery(UserPo.class)
                .eq(UserPo::getUsername, username)
                .last(SqlConstant.LIMIT_1));

        if (userPo == null) {
            throw new BusinessException("用户名不存在");
        }
        String passwordEncrypt = SecureUtil.aes(LOGIN_AES_CRYPTO_KEY_BYTE).encryptBase64(password);
        if (!StrUtil.equals(userPo.getPassword(), passwordEncrypt)) {
            throw new BusinessException("密码错误");
        }

        CurrentUserDto currentUserDto = BeanUtil.copyProperties(userPo, CurrentUserDto.class);

        StpUtil.login(currentUserDto.getId());
        SaSession tokenSession = StpUtil.getTokenSession();
        tokenSession.set(SA_MODEL_KEY_USER, currentUserDto);
        tokenSession.set(SA_MODEL_KEY_PERMISSION, StpUtil.getPermissionList());
        tokenSession.set(SA_MODEL_KEY_ROLE, StpUtil.getRoleList());
        return StpUtil.getTokenValue();
    }

}
